package com.tinusgraglin.enclusiv.ui.screens

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.tinusgraglin.enclusiv.EnclusivApp
import com.tinusgraglin.enclusiv.R
import com.tinusgraglin.enclusiv.datalayer.ShowedArticleProfile
import com.tinusgraglin.enclusiv.datalayer.UserArticleStats
import com.tinusgraglin.enclusiv.ui.viewmodel.ArticleActivityViewModel
import com.tinusgraglin.enclusiv.ui.EnclusivViewModelFactory
import com.tinusgraglin.enclusiv.ui.theme.EnclusivTheme
import kotlinx.coroutines.launch

class ArticleActivity : ComponentActivity() {
    private val viewModel: ArticleActivityViewModel by viewModels {
        EnclusivViewModelFactory()
    }
    private var idx: Int = 0
    private var liked: MutableState<Boolean> = mutableStateOf(false)
    private var faved: MutableState<Boolean> = mutableStateOf(false)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            EnclusivTheme {
                Surface {
                    val idArticlePair = intent.getSerializableExtra("ARTICLE_DATA") as Pair<Int, ShowedArticleProfile>
                    idx = idArticlePair.first
                    ArticleScreen(showedArticleProfile = idArticlePair.second)
                }
            }
        }
    }

    override fun onDestroy() {
        setResult(RESULT_OK, Intent().putExtra("USER_ARTICLE_STATS", Pair(idx, UserArticleStats(liked.value, faved.value))))
        super.onDestroy()
    }

    override fun onBackPressed() {
        setResult(RESULT_OK, Intent().putExtra("USER_ARTICLE_STATS", Pair(idx, UserArticleStats(liked.value, faved.value))))
        super.onBackPressed()
    }

    @Composable
    fun ArticleScreen(showedArticleProfile: ShowedArticleProfile) {
        liked = remember { mutableStateOf(showedArticleProfile.userArticleStats!!.like) }
        faved = remember { mutableStateOf(showedArticleProfile.userArticleStats!!.collect) }
        val scope = rememberCoroutineScope()

        Box(modifier = Modifier.fillMaxSize()) {
            Column {
                IconButton(
                    modifier = Modifier.align(Alignment.Start),
                    onClick = {
                        onBackPressed()
                    }
                ) {
                    Icon(
                        modifier = Modifier.size(20.dp),
                        painter = painterResource(R.drawable.back),
                        contentDescription = "Icon Button: Back",
                    )
                }
                Spacer(Modifier.height(4.dp))
                LazyColumn (modifier = Modifier
                    .padding(horizontal = 10.dp)
                    .padding(bottom = 60.dp)) {
                    item {
                        Text(
                            text = showedArticleProfile.title,
                            fontSize = 22.sp,
                            fontWeight = FontWeight.Bold,
                            softWrap = true,
                            maxLines = 4,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                    item {
                        Row(modifier = Modifier.padding(10.dp), verticalAlignment = Alignment.CenterVertically) {
                            AsyncImage(
                                modifier = Modifier
                                    .size(32.dp)
                                    .clip(CircleShape),
                                contentDescription = "Image: User Profile Image",
                                imageLoader = EnclusivApp.globalCoilImageLoader,
                                model = ImageRequest.Builder(LocalContext.current).apply {
                                    data(showedArticleProfile.authorProfileImgUrl)
                                    placeholder(R.drawable.user)
                                }.build()
                            )
                            Spacer(Modifier.width(10.dp))
                            Text(
                                text = showedArticleProfile.authorName,
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold,
                                softWrap = true,
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                        }
                    }
                    itemsIndexed(showedArticleProfile.contentSegments) { i, it ->
                        Text(
                            text = it,
                            fontSize = 16.sp,
                        )
                        Spacer(modifier = Modifier.height(10.dp))
                        if (i <= showedArticleProfile.imageUrls.lastIndex) {
                            AsyncImage(
                                modifier = Modifier
                                    .clip(RoundedCornerShape(10.dp)),
                                contentDescription = "Image: User Profile Image",
                                imageLoader = EnclusivApp.globalCoilImageLoader,
                                model = ImageRequest.Builder(LocalContext.current).apply {
                                    data(showedArticleProfile.imageUrls[i])
                                    placeholder(R.drawable.user)
                                }.build()
                            )
                        }
                    }
                }
            }
            // bottom
            Row(modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(vertical = 8.dp)
                .padding(end = 8.dp)) {
                IconToggleButton(checked = liked.value, onCheckedChange = {
                    val deferred = viewModel.like(showedArticleProfile.id, !it)
                    scope.launch {
                        try {
                            deferred.await()
                            liked.value = it
                        } catch (e: Exception) {
                            Log.d("##DBG 500", "message: ${e.message}")
                            e.printStackTrace()
                        }
                    }
                }) {
                    Icon(
                        painter = painterResource(if (liked.value) R.drawable.liked else R.drawable.like),
                        contentDescription = "Icon Button: Like",
                        modifier = Modifier.size(32.dp)
                    )
                }
                Spacer(Modifier.width(4.dp))
                IconToggleButton(checked = faved.value, onCheckedChange = {
                    val deferred = viewModel.fav(showedArticleProfile.id, !it)
                    scope.launch {
                        try {
                            deferred.await()
                            faved.value = it
                        } catch (e: Exception) {
                            Log.d("##DBG 500", "message: ${e.message}")
                            e.printStackTrace()
                        }
                    }
                }) {
                    Icon(
                        painter = painterResource(if (faved.value) R.drawable.loved else R.drawable.love),
                        contentDescription = "Icon Button: Fav",
                        modifier = Modifier.size(32.dp)
                    )
                }
            }
        }
    }
}